﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AccountingLibs;
using Lists;
using System.Linq;
using System.Data.Objects;

using Vouchers;
using BasicForms;
using System.Data.SqlClient;

namespace BanLe
{
    public partial class FrmEditHoaDonBanLe : FrmBase
    {
        #region DanhSachChungTu property
        private DanhSachChungTu _DanhSachChungTu;
        public DanhSachChungTu DanhSachChungTu
        {
            get
            {
                return _DanhSachChungTu;
            }
            set
            {
                _DanhSachChungTu = value;
            }
        }
        #endregion

        #region ChungTu property
        private ChungTu _ChungTu;
        public ChungTu ChungTu
        {
	        get 
	        { 
		        return _ChungTu;
	        }
	        set 
	        {
		        _ChungTu = value;
	        }
        }
        #endregion

        #region EditState property
        private EditState _EditState;
        public EditState EditState
        {
            get
            {
                return _EditState;
            }
            set
            {
                _EditState = value;
            }
        }
        #endregion

        public FrmEditHoaDonBanLe()
        {
            InitializeComponent();
            
            DieuKienTimKiemChungTu dieuKienTimKiemChungTu = new DieuKienTimKiemChungTu();
            dieuKienTimKiemChungTu.LoaiChungTu = DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanLe");

            _DanhSachChungTu = new DanhSachChungTu();
            _DanhSachChungTu.LoadFromDB(dieuKienTimKiemChungTu.BuildSqlStatement(1000000,1));
        }

        private void FrmEditHoaDonBanLe_Load(object sender, EventArgs e)
        {
            GuiUtilities.FrmProgressBar.StartShowProgress();

            lblTenCuaHang.Text = string.Format("{0}, {1}", AccountingLibs.LocalSettings.HeThong.TenCuaHang, AccountingLibs.LocalSettings.HeThong.DiaChi);
            lblNguoiBan.Text = CustomSecurity.User.CurUser.FullName;

            MayTinh mt = DanhMucMayTinh.Instance.GetByHardwareID(AccountingLibs.LocalSettings.HeThong.HardwareID);
            if (mt != null)
                lblTenMay.Text = mt.Ten;


            #region cmbDoiTuong
            cmbDoiTuong.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucKhachHang().DataView;
            cmbDoiTuong.DisplayColumn = "Ten";
            cmbDoiTuong.ValueColumn = "ID";
            cmbDoiTuong.AddVisibleColumn("Ma", "Mã");
            cmbDoiTuong.AddVisibleColumn("Ten", "Tên");
            #endregion

            #region cmbKho
            cmbKho.DataSource = DanhMucKho.Instance.DataView;
            cmbKho.DisplayColumn = "Ten";
            cmbKho.ValueColumn = "ID";
            cmbKho.AddVisibleColumn("Ma", "Mã");
            cmbKho.AddVisibleColumn("Ten", "Tên");
            #endregion

            #region cmbMaHang
            cmbMaHang.DataSource = DanhMucVatTuHangHoa.GetDanhMucHangHoa().DataView;
            cmbMaHang.PopupWidth = 500;
            cmbMaHang.PopupHeight = 297;
            cmbMaHang.DisplayColumn = "Ma";
            cmbMaHang.ValueColumn = "ID";
            cmbMaHang.AddVisibleColumn("Ma", "Mã", 100, 1);
            cmbMaHang.AddVisibleColumn("Ten", "Tên", 320, 2);
            cmbMaHang.AddVisibleColumn("GiaBia", "Giá bán", 80, 3);
            #endregion

            #region cmbThueSuat
            cmbThueSuat.DataSource = DanhMucThueSuat.Instance.DataView;
            cmbThueSuat.DisplayColumn = "Ten";
            cmbThueSuat.ValueColumn = "ID";
            cmbThueSuat.AddVisibleColumn("Ma", "Mã");
            cmbThueSuat.AddVisibleColumn("Ten", "Tên");
            #endregion

            #region DataForGrid
            CustomControls.DataForGrid dataForGrid = null;

            dataForGrid = new CustomControls.DataForGrid();
            customGridKhoanMuc.PopupHeight = 297;
            customGridKhoanMuc.PopupWidth = 500;

            dataForGrid = new CustomControls.DataForGrid();
            dataForGrid.DataSource = DanhMucVatTuHangHoa.GetDanhMucHangHoa().DataView;
            dataForGrid.AddVisibleColumn("Ma", "Mã", 100, 1);
            dataForGrid.AddVisibleColumn("Ten", "Tên", 320, 2);
            dataForGrid.AddVisibleColumn("GiaBia", "Giá bán", 80, 3);
            dataForGrid.DisplayColumn = "Ma";
            dataForGrid.ValueColumn = "ID";
            customGridKhoanMuc.HtDataForGrid.Add("VatTuHangHoa1ID", dataForGrid);
            #endregion


            #region Default values
            DoiTuongNghiepVu khachLe = DanhMucDoiTuongNghiepVu.GetDanhMucKhachHang().GetByMa("KL");
            if (khachLe != null)
            {
                cmbDoiTuong.EditValue = khachLe.ID;
            }

            cmbMaHang.EditValue = null;
            if ((Guid)AccountingLibs.LocalSettings.HeThong.KhoID != Guid.Empty)
                cmbKho.EditValue = AccountingLibs.LocalSettings.HeThong.KhoID;
            //if ((Guid)AccountingLibs.LocalSettings.HeThong.ThueSuatID != Guid.Empty)
                cmbThueSuat.EditValue = AccountingLibs.LocalSettings.HeThong.ThueSuatID;
            //else
            //    cmbThueSuat.EditValue = DanhMucThueSuat.Instance[0];
            #endregion

            Reset();
            SetNumberDisplayFormat();

            GuiUtilities.FrmProgressBar.FinishShowProgress();
            timer.Start();
        }

        protected void SetEditState(EditState editState)
        {
            _EditState = editState;
            base.SetEditState(EditState);
            switch (editState)
            {
                case EditState.CreatingNew:
                    btnSave.Enabled = true;
                    btnSaveAndPrint.Enabled = true;
                    btnPrint.Enabled = false;
                    //btnCancel.Enabled = true;
                    btnCreateNew.Text = "Hủy (F2)";
                    break;
                case EditState.Saved:
                    btnSave.Enabled = false;
                    btnSaveAndPrint.Enabled = false;
                    btnPrint.Enabled = true;
                    //btnCancel.Enabled = false;
                    btnCreateNew.Text = "Thêm (F2)";
                    break;
            }
        }
        protected void SetNumberDisplayFormat()
        {
            FormatTextEdit(txtTongSoLuong, BasicForms.TextFormatType.Money);
            FormatTextEdit(txtTongGiaBia, BasicForms.TextFormatType.Money);
            FormatTextEdit(txtTongSoTien, BasicForms.TextFormatType.Money);
            FormatTextEdit(txtSoTienKhachDua, BasicForms.TextFormatType.Money);
            FormatTextEdit(txtSoTienTraLai, BasicForms.TextFormatType.Money);
            FormatNumberInGridView(customGridKhoanMuc.gridViewKhoanMuc);

            txtTongSoLuong.Properties.ReadOnly = true;
            txtTongGiaBia.Properties.ReadOnly = true;
            txtTongSoTien.Properties.ReadOnly = true;
            txtSoTienTraLai.Properties.ReadOnly = true;

            customGridKhoanMuc.gridViewKhoanMuc.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
            customGridKhoanMuc.gridViewKhoanMuc.Columns["VatTuHangHoa1ID"].OptionsColumn.AllowEdit = false;
            customGridKhoanMuc.gridViewKhoanMuc.Columns["Value4"].OptionsColumn.AllowEdit = false;
            customGridKhoanMuc.gridViewKhoanMuc.Columns["Value6"].OptionsColumn.AllowEdit = false;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.F2:
                case Keys.F5:
                    Reset();
                    return true;
                    break;
                case Keys.F4:
                    Save(); ;
                    return true;
                    break;
                //case Keys.F5:
                //    Cancel();
                //    return true;
                case Keys.F8:
                    SaveAndPrint();
                    return true;
                    break;
                case Keys.F7:
                case Keys.F12:
                    if (_EditState == EditState.Saved)
                    {
                        Print();
                    }
                    return true;
                    break;
                case Keys.Alt | Keys.K:
                    txtSoTienKhachDua.SelectAll();
                    txtSoTienKhachDua.Focus();
                    return true;
                    break;
                case Keys.Alt | Keys.H:
                    cmbMaHang.Focus();
                    return true;
                    break;
                default:
                    return base.ProcessCmdKey(ref msg, keyData);
                    break;
            }
        }

        private void Reset()
        {
            GuiUtilities.FrmProgressBar.StartShowProgress();

            cmbMaHang.Focus();
            _ChungTu = _DanhSachChungTu.CreateNew(DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanLe"));
            _ChungTu.LoadDanhSachChungTuPhuThuoc();
            ChungTu phieuXuatKho = _ChungTu.DanhSachChungTuPhuThuoc.CreateNew(DanhMucLoaiChungTu.Instance.GetByMa("PhieuXuatKho"));
            Kho khoXuat = DanhMucKho.Instance.GetByID((Guid)cmbKho.EditValue);
            if(khoXuat!=null)
                phieuXuatKho.So = AccountingLibs.CommonLib.GetSoChungTuMacDinh(khoXuat.Ma + "/PX" + @"/", 7, false);
            else
                phieuXuatKho.So = AccountingLibs.CommonLib.GetSoChungTuMacDinh("XL", 7, true);
            
            _ChungTu.DanhSachChungTuPhuThuoc.Add(phieuXuatKho);

            #region Bound data for customGridKhoanMuc
            phieuXuatKho.LoadKhoanMuc();
            customGridKhoanMuc.DataSource = phieuXuatKho.DanhSachKhoanMuc.DataTable;
            customGridKhoanMuc.FormatColumns(AccountingLibs.Config.GiaoDienChungTu.Filter(_ChungTu.LoaiChungTuID));
            _ChungTu.DanhSachChungTuPhuThuoc[0].DanhSachKhoanMuc.DataTable.ColumnChanged += new DataColumnChangeEventHandler(DataTable_ColumnChanged);
            _ChungTu.DanhSachChungTuPhuThuoc[0].DanhSachKhoanMuc.DataTable.RowChanged += new DataRowChangeEventHandler(DataTable_RowChanged);
            _ChungTu.DanhSachChungTuPhuThuoc[0].DanhSachKhoanMuc.DataTable.RowDeleted += new DataRowChangeEventHandler(DataTable_RowDeleted);
            #endregion

            cmbMaHang.EditValue = null;
            txtSo.Text = AccountingLibs.CommonLib.GetSoChungTuMacDinh(DanhMucLoaiChungTu.Instance.GetByMa("HoaDonBanLe").ID, true);
            dateNgay.EditValue = AccountingLibs.CommonLib.GetSystemDateTime();
            txtTongSoLuong.EditValue = (decimal)0;
            txtTongGiaBia.EditValue = (decimal)0;
            txtTongSoTien.EditValue = (decimal)0;
            txtSoTienKhachDua.EditValue = (decimal)0;
            txtSoTienTraLai.EditValue = (decimal)0;

            SetEditState(AccountingLibs.EditState.CreatingNew);

            GuiUtilities.FrmProgressBar.FinishShowProgress();
        }

        protected void SaveAndPrint()
        {
            if (_EditState == EditState.CreatingNew)
            {
                if (Save())
                    Print();
            }
        }

        protected bool Save()
        {
            if (_EditState != EditState.CreatingNew) return false;
            btnSave.Focus();
            try
            {
                if (!CheckFullInfo()) return false;
                _ChungTu.So = txtSo.Text;
                _ChungTu.Ngay = new NullableDate(dateNgay.DateTime);
                _ChungTu.DoiTuongNghiepVu1ID = (Guid)cmbDoiTuong.EditValue;
                _ChungTu.TenNguoiThucHien = DanhMucDoiTuongNghiepVu.Instance.GetByID(_ChungTu.DoiTuongNghiepVu1ID).Ten;
                _ChungTu.TaiKhoan1ID = (Guid)DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("BanLe_NoTienThuVe");
                _ChungTu.TaiKhoan2ID = (Guid)DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("VatDauRa");
                _ChungTu.TaiKhoan4ID = (Guid)DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("BanLe_CoDoanhThu");
                _ChungTu.ThueSuat1ID = (Guid)cmbThueSuat.EditValue;
                _ChungTu.TienTeID = DanhMucTienTe.Instance.GetTienHoachToan().ID;
                _ChungTu.TyGiaThucTe = 1;
                _ChungTu.SoTienNT = _ChungTu.SoTienQD = (decimal)txtTongSoTien.EditValue;   //tien phai thanh toan
                _ChungTu.Value1 = (decimal)txtTongGiaBia.EditValue;             //gia bia
                _ChungTu.Value2 = (decimal)txtSoTienKhachDua.EditValue;         //tien dua
                _ChungTu.Value3 = _ChungTu.Value2 - _ChungTu.SoTienNT;          //tien thua
                _ChungTu.Value4 = _ChungTu.Value1 - _ChungTu.SoTienNT;          //tien chiet khau
                decimal thueSuat = DanhMucThueSuat.Instance.GetByID(_ChungTu.ThueSuat1ID).MucThueSuat;
                _ChungTu.Value6 = _ChungTu.SoTienQD / (1 + thueSuat); //tien hang
                _ChungTu.Value5 = _ChungTu.SoTienQD * thueSuat / (1 + thueSuat);//tien thue VAT

                _ChungTu.GhiSo = true;

                ChungTu phieuXuatKho = _ChungTu.DanhSachChungTuPhuThuoc[0];
                phieuXuatKho.LoaiChungTuID = DanhMucLoaiChungTu.Instance.GetByMa("PhieuXuatKho").ID;
                phieuXuatKho.DinhKhoan = false;

                GuiUtilities.FrmProgressBar.StartShowProgress();
                GuiUtilities.FrmProgressBar.Status = "Đang tính giá vốn hàng xuất kho";
                try
                {
                    foreach (KhoanMucChungTu khoanMuc in phieuXuatKho.DanhSachKhoanMuc)
                    {
                        khoanMuc.Value2 = VatTuHangHoa.CalculateGiaXuatKho(khoanMuc.VatTuHangHoa1ID, (Guid)cmbKho.EditValue, dateNgay.DateTime, khoanMuc.Value1);
                    }
                }
                catch (Exception ex)
                {
                }
                GuiUtilities.FrmProgressBar.FinishShowProgress();

                phieuXuatKho.Ngay = _ChungTu.Ngay;
                phieuXuatKho.SoChungTuGoc = txtSo.Text;
                phieuXuatKho.DoiTuongNghiepVu1ID = (Guid)cmbDoiTuong.EditValue;
                phieuXuatKho.TenNguoiThucHien = cmbDoiTuong.Text;
                phieuXuatKho.DienGiai = "Xuất kho bán lẻ";
                phieuXuatKho.TaiKhoan1ID = (Guid)DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("BanLe_NoGiaVon");
                phieuXuatKho.TaiKhoan2ID = (Guid)DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("BanLe_CoXuatKho");
                phieuXuatKho.TienTeID = _ChungTu.TienTeID;
                phieuXuatKho.TyGiaThucTe = _ChungTu.TyGiaThucTe;
                phieuXuatKho.DataRow["SoTienNT"] = _ChungTu.SoTienNT;
                phieuXuatKho.DataRow["SoTienQD"] = _ChungTu.SoTienNT;
                phieuXuatKho.Kho1ID = (Guid)cmbKho.EditValue;
                phieuXuatKho.DangXuatID = DanhMucDangXuat.Instance.GetByProperty("IsBuildInRecord", true).ID;

                _ChungTu.SaveAndGhiSo();
                SetEditState(EditState.Saved);
                return true;
            }
            catch (CustomException cusEx)
            {
                if (cusEx.ExceptionType == ExceptionType.SoChungTuDaCo)
                {
                    txtSo.Text = AccountingLibs.CommonLib.GetSoChungTuMacDinh(_ChungTu.LoaiChungTuID);
                    if (_ChungTu.DanhSachChungTuPhuThuoc.Count >= 1)
                    {
                        ChungTu phieuXuatKho = _ChungTu.DanhSachChungTuPhuThuoc[0];
                        phieuXuatKho.So = AccountingLibs.CommonLib.GetSoChungTuMacDinh("XL", 7, true);
                    }
                }
                MessageBox.Show(cusEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                return false;
            }
        }

        protected void Print()
        {
            if (_ChungTu != null && _ChungTu.ChungTuID != Guid.Empty)
            {
                _ChungTu.PrintChungTu();
            }
        }

        private void FillTongCong()
        {
            try
            {
                decimal tienHangChuaThue = 0;
                decimal tongTheoGiaBia = 0, tongSoTien = 0;
                foreach (DataRow row in _ChungTu.DanhSachChungTuPhuThuoc[0].DanhSachKhoanMuc.DataTable.Rows)
                {
                    if (row["Value5"] is decimal)
                        tienHangChuaThue += (decimal)row["Value5"];
                    if (row["Value7"] is decimal)
                        tongSoTien += (decimal)row["Value7"];
                    if (row["Value13"] is decimal)
                        tongTheoGiaBia += (decimal)row["Value13"];
                }

                txtTongGiaBia.EditValue = tongTheoGiaBia;
                txtTongSoTien.EditValue = tongSoTien;
                txtTongSoLuong.EditValue = _ChungTu.DanhSachChungTuPhuThuoc[0].DanhSachKhoanMuc.DataTable.Compute("SUM (Value1)", "VatTuHangHoa1ID IS NOT NULL"); ;
            }catch(Exception ex)
            {
                MessageBox.Show("Lỗi chương trình, đề nghị báo cho đv phần mềm " + ex.ToString());
            }
        }
        protected bool CheckFullInfo()
        {
            if (txtSo.Text == "")
            {
                txtSo.Focus();
                throw new CustomException("Hãy nhập số");
                return false;
            }
            if (dateNgay.Text == "")
            {
                dateNgay.Focus();
                throw new CustomException("Hãy nhập ngày");
                return false;
            }
            if (!(cmbDoiTuong.EditValue is Guid) || (Guid)cmbDoiTuong.EditValue == Guid.Empty)
            {
                cmbDoiTuong.Focus();
                throw new CustomException("Hãy chọn khách hàng");
                return false;
            }
            if (!(cmbKho.EditValue is Guid) || (Guid)cmbKho.EditValue == Guid.Empty)
            {
                cmbKho.Focus();
                throw new CustomException("Hãy chọn kho xuất hàng");
                return false;
            }
            if (!(cmbThueSuat.EditValue is Guid) || (Guid)cmbThueSuat.EditValue == Guid.Empty)
            {
                cmbThueSuat.Focus();
                throw new CustomException("Hãy chọn thuế suất");
                return false;
            }
            if (_ChungTu.DanhSachChungTuPhuThuoc[0].DanhSachKhoanMuc.Count == 0 || (decimal)txtTongSoLuong.EditValue == 0)
            {
                cmbMaHang.Focus();
                throw new CustomException("Hãy chọn mặt hàng cho hóa đơn");
                return false;
            }
            return true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }
        private void btnSaveAndPrint_Click(object sender, EventArgs e)
        {
            SaveAndPrint();
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            Print();
        }
        private void btnCreateNew_Click(object sender, EventArgs e)
        {
            Reset();
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
        void DataTable_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            FillTongCong();
        }
        void DataTable_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            try
            {
                DataRow row = e.Row;
                switch (e.Column.Caption)
                {
                    case "VatTuHangHoa1ID":
                        if (row["VatTuHangHoa1ID"] is Guid)
                        {
                            if (!(row["Value1"] is decimal)) row["Value1"] = 1;

                            VatTuHangHoa vatTuHangHoa = DanhMucVatTuHangHoa.Instance.GetByID((Guid)row["VatTuHangHoa1ID"]);
                            row["Value8"] = vatTuHangHoa.ChietKhau;
                            row["Value12"] = vatTuHangHoa.GiaBia;
                            row["Value2"] = vatTuHangHoa.GiaBia;
                        }
                        break;
                    case "Value1"://SoLuong
                        if (row["Value1"] is decimal)
                        {
                            if (row["Value2"] is decimal) row["Value3"] = (decimal)row["Value1"] * (decimal)row["Value2"];
                            if (row["Value4"] is decimal) row["Value5"] = (decimal)row["Value1"] * (decimal)row["Value4"];
                            if (row["Value6"] is decimal) row["Value7"] = (decimal)row["Value1"] * (decimal)row["Value6"];
                            if (row["Value12"] is decimal) row["Value13"] = (decimal)row["Value1"] * (decimal)row["Value12"];
                        }
                        break;
                    case "Value2"://DonGia
                        if (row["Value1"] is decimal && (decimal)row["Value2"] > 0)
                        {
                            if (!(row["Value3"] is decimal) || (decimal)row["Value3"] != (decimal)row["Value1"] * (decimal)row["Value2"])
                                row["Value3"] = (decimal)row["Value1"] * (decimal)row["Value2"];
                        }
                        break;
                    case "Value3"://Tien nhap kho NT
                        //TienXKQD
                        if (row["Value1"] is decimal && (decimal)row["Value1"] > 0)
                        {
                            if (!(row["Value2"] is decimal) || (decimal)row["Value2"] != (decimal)row["Value3"] / (decimal)row["Value1"])
                                row["Value2"] = (decimal)row["Value3"] / (decimal)row["Value1"];
                        }
                        break;
                    case "Value4"://DonGiaNT
                        if (row["Value1"] is decimal && row["Value4"] is decimal)
                        {
                            row["Value5"] = (decimal)row["Value1"] * (decimal)row["Value4"];
                        }
                        break;
                    case "Value6"://
                        if ((Guid)cmbThueSuat.EditValue != Guid.Empty)
                        {
                            Guid thueSuatID = (Guid)cmbThueSuat.EditValue;
                            row["Value4"] = (decimal)row["Value6"] / (1 + DanhMucThueSuat.Instance.GetByID(thueSuatID).MucThueSuat);
                        }
                        if (row["Value1"] is decimal && row["Value6"] is decimal)
                        {
                            row["Value7"] = (decimal)row["Value1"] * (decimal)row["Value6"];
                        }
                        break;
                    case "Value8":
                        if (row["Value12"] != DBNull.Value && row["Value8"] != DBNull.Value)
                        {
                            row["Value6"] = (decimal)row["Value12"] * (100 - (decimal)row["Value8"]) / 100;
                        }
                        break;
                    case "Value12":
                        if (row["Value12"] != DBNull.Value && row["Value8"] != DBNull.Value)
                        {
                            row["Value6"] = (decimal)row["Value12"] * (100 - (decimal)row["Value8"]) / 100;
                        }
                        e.Row["Value13"] = (decimal)e.Row["Value1"] * (decimal)e.Row["Value12"];
                        break;
                }
            }
            catch (Exception ex)
            {
            }
        }
        void DataTable_RowDeleted(object sender, DataRowChangeEventArgs e)
        {
            FillTongCong();
        }

        private void txtTongSoTien_EditValueChanged(object sender, EventArgs e)
        {
            if (txtSoTienKhachDua.EditValue is decimal && txtTongSoTien.EditValue is decimal)
            {
                if ((decimal)txtSoTienKhachDua.EditValue >= (decimal)txtTongSoTien.EditValue)
                {
                    lblTienThua.Text = "Tiền thừa";
                    txtSoTienTraLai.EditValue = (decimal)txtSoTienKhachDua.EditValue - (decimal)txtTongSoTien.EditValue;
                }
                else
                {
                    lblTienThua.Text = "Tiền thiếu ";
                    txtSoTienTraLai.EditValue = (decimal)txtTongSoTien.EditValue -(decimal)txtSoTienKhachDua.EditValue;
                }
            }
        }
        private void txtSoTienKhachDua_EditValueChanged(object sender, EventArgs e)
        {
            if (txtSoTienKhachDua.EditValue is decimal && txtTongSoTien.EditValue is decimal)
            {
                if ((decimal)txtSoTienKhachDua.EditValue >= (decimal)txtTongSoTien.EditValue)
                {
                    lblTienThua.Text = "Tiền thừa";
                    txtSoTienTraLai.EditValue = (decimal)txtSoTienKhachDua.EditValue - (decimal)txtTongSoTien.EditValue;
                    txtSoTienTraLai.BackColor = Color.SkyBlue;
                }
                else
                {
                    lblTienThua.Text = "Tiền thiếu ";
                    txtSoTienTraLai.EditValue = (decimal)txtTongSoTien.EditValue - (decimal)txtSoTienKhachDua.EditValue;
                    txtSoTienTraLai.BackColor = Color.LightSalmon;
                }
            }
        }
        private void txtSoTienKhachDua_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void btnThongKe_Click(object sender, EventArgs e)
        {
            ReportGenerators.BanHang.ThongKeBanHangLe.FrmThongKeBanLe frm = new ReportGenerators.BanHang.ThongKeBanHangLe.FrmThongKeBanLe();
            frm.Show();
        }
        private void cmbDoiTuong_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                SendKeys.Send("{TAB}");
            }
        }
        private void cmbKho_EditValueChanged(object sender, EventArgs e)
        {
            if (cmbKho.EditValue is Guid && (Guid)cmbKho.EditValue != Guid.Empty && (Guid)cmbKho.EditValue != AccountingLibs.LocalSettings.HeThong.KhoID)
            {
                AccountingLibs.LocalSettings.HeThong.KhoID = (Guid)cmbKho.EditValue;
                AccountingLibs.LocalSettings.HeThong.Save2File();
            }
        }

        private void cmbMaHang_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                VatTuHangHoa selected = DanhMucVatTuHangHoa.Instance.GetByProperty("Ma", cmbMaHang.Text);
                if (selected != null && _ChungTu != null)
                {
                    DataRow[] existedRows = _ChungTu.DanhSachChungTuPhuThuoc[0].DanhSachKhoanMuc.DataTable.Select("VatTuHangHoa1ID = '" + selected.ID.ToString() + "'");
                    if (existedRows.Length > 0)
                    {
                        existedRows[0]["Value1"] = (decimal)existedRows[0]["Value1"] + 1;
                        return;
                    }
                    else
                    {
                        KhoanMucChungTu addedNew = _ChungTu.DanhSachChungTuPhuThuoc[0].DanhSachKhoanMuc.CreateNew();
                        addedNew.VatTuHangHoa1ID = selected.ID;
                        addedNew.Value1 = 1;
                        addedNew.Value12 = selected.GiaBia;
                        addedNew.Value8 = selected.ChietKhau;
                        _ChungTu.DanhSachChungTuPhuThuoc[0].DanhSachKhoanMuc.Add(addedNew);
                    }
                }
                else
                {
                    MessageBox.Show("Mã sách không tồn tại");
                }
                cmbMaHang.Select();
            }
        }
        private void cmbMaHang_EditValueChanged(object sender, EventArgs e)
        {
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            GuiUtilities.FrmProgressBar.StartShowProgress();
            GuiUtilities.FrmProgressBar.Status = "Đang lấy danh mục hàng hóa mới nhất";
            try
            {
                DanhMucVatTuHangHoa.Instance.LoadFromDB();
            }
            catch (Exception ex)
            {
            }
            GuiUtilities.FrmProgressBar.FinishShowProgress();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            btnReload_Click(null, null);
        }

        private void btnTinhGiaXuatKho_Click(object sender, EventArgs e)
        {
           
        }

        #region Xu ly hien thi thong tin ton kho
        private void cmbMaHang_RequireShowThongTinTonKho(object sender, Guid vatTuHangHoaID)
        {
            if (!(cmbKho.EditValue is Guid) || (Guid)cmbKho.EditValue == Guid.Empty) return;
            try
            {
                TinhToanVaHienThiTon((Guid)cmbKho.EditValue, vatTuHangHoaID);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void cmbMaHang_RequireHideThongTinTonKho(object sender)
        {
            lblThongTinTonKho.Visible = false;
        }

        private void customGridKhoanMuc_RequireShowThongTinTonKho(object sender, Guid vatTuHangHoaID)
        {
            if (!(cmbKho.EditValue is Guid) || (Guid)cmbKho.EditValue == Guid.Empty) return;
            try
            {
                TinhToanVaHienThiTon((Guid)cmbKho.EditValue, vatTuHangHoaID);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void customGridKhoanMuc_RequireHideThongTinTonKho(object sender)
        {
            lblThongTinTonKho.Visible = false;
        }

        private void TinhToanVaHienThiTon(Guid khoID, Guid vatTuHangHoaID)
        {
            if (khoID == Guid.Empty || vatTuHangHoaID == Guid.Empty) return;
            SqlConnection con = new SqlConnection(LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                VatTuHangHoa vthh = DanhMucVatTuHangHoa.Instance.GetByID(vatTuHangHoaID);
                TonKho tonTaiKhoNay = TonKho.CalculateFromDB(cmd, dateNgay.DateTime, khoID, vatTuHangHoaID);
                TonKho tonToanBo = TonKho.CalculateFromDB(cmd, dateNgay.DateTime, vatTuHangHoaID);
                TonKho tongNhap = TonKho.CalculateTongMuaTheoThoiDiemKhoaSoGanNhat(cmd, dateNgay.DateTime, vatTuHangHoaID);
                TonKho tongXuat = TonKho.CalculateTongBanTheoThoiDiemKhoaSoGanNhat(cmd, dateNgay.DateTime, vatTuHangHoaID);

                //lblThongTinTonKho.Text = string.Format("CK: {3}| Tại {0}: {1} | Tồn tổng: {2}",
                //    cmbKho.Text, (int)tonTaiKhoNay.SoLuong, (int)tonToanBo.SoLuong, vthh.ChietKhauBan);

                lblThongTinTonKho.Text = string.Format("CK: {0} | Mua: {1} | Bán: {2}  | Tổng tồn: {3} | Tồn tại quầy: {4}",
                    vthh.ChietKhau.ToString("0.#"), (int)tongNhap.SoLuong, (int)tongXuat.SoLuong, (int)tonToanBo.SoLuong, (int)tonTaiKhoNay.SoLuong);
                lblThongTinTonKho.Visible = true;
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new CustomException(ex.Message);
                }
            }
            finally
            {
                con.Close();
            }
        }
        #endregion  
    }
}
